import api from "../../utils/api"; // 引入api接口管理文件
import customerApi from "../../utils/customerApi";
import { LOCATION_ICON, SEARCH_ICON } from "../../constant/index";
import { withTokenFn, throttle, throttle2 } from "../../utils/util";

// 获取应用实例
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    locationIcon: LOCATION_ICON,
    searchIcon: SEARCH_ICON,
    envVersion: "",
    loading: true, // 全局loading
    feedLoading: false, // 信息流loading
    locationName: "全国",
    typeList: null,
    provincesList: null,
    dataList: null,
    pageNum: 1,
    totalPage: 1,
    areaTxt: "",
    catId: "",
    banner: [],
    pageFooterType: "",
    pageErrorFixed: false,
    chooseTypeItem: null,
    showWaringMessage: false,
    adInfo: null,
    privacyData: {},
    filterResult: {
      areaId: "",
      minDistanceToMax: null,
      minPayPriceToMax: null,
      gender: null,
      vaccineCategoryId: null,
      "injectObjects[]": null,
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("options: index", options);
    this.getNetworkType();
    this.handleOptions(options || {});
    this.handleOther();
  },

  onShow() {
    this.getMiniAppFullScreenAdvV2();
    this.getShowPrivacy();
  },
  onHide() {
    this.setData({
      privacyData: {}
    })
  },
  handleOther() {
    const {
      miniProgram: { envVersion },
    } = wx.getAccountInfoSync();
    if (envVersion === "develop" || envVersion === "trial") {
      wx.setEnableDebug({
        enableDebug: true,
      });
    }
    let devVersion = wx.getStorageSync("devVersion");
    this.setData({
      envVersion: envVersion,
      devVersion: devVersion,
      switch1Checked: devVersion,
    });
  },

  handleOptions(options = {}) {
    const { filterResult } = this.data;
    // 将扫码携带的参数都放在全局globalData中
    const sceneObj = (options.scene && this.handleScene(options.scene)) || {};
    if (sceneObj.vaccineCategoryId) {
      options.catId = +vaccineCategoryId;
    }
    if (options.areaId) {
      this.areaInfo(+options.areaId);
      filterResult["areaId"] = +options.areaId;
    }

    if (options.catId) {
      filterResult["vaccineCategoryId"] = +options.catId;
    }
    app.globalData = {
      ...app.globalData,
      ...sceneObj,
    };
    this.setData(
      {
        filterResult,
        catId: +options.catId || "",
      },
      () => {
        this.getSetting();
      }
    );
  },

  /**
   * @description: 处理扫码携带的参数
   * @param {*} query 入参
   * @return {*}
   */
  handleScene(scene = "") {
    const sceneObj = {};
    const sceneArr = decodeURIComponent(scene).split("&");
    sceneArr.forEach((item) => {
      if (item) {
        let sceneItem = item.split("=");
        sceneObj[sceneItem[0]] = sceneItem[1];
      }
    });
    return sceneObj;
  },

  choosetype(list, index) {
    this.setData({
      chooseTypeItem: list[index],
    });
  },

  /**
   * @description: 检查网络
   */
  getNetworkType() {
    wx.getNetworkType().then((res) => {
      res.getNetworkType === "none" && this.handlePageError("error");
    });
  },

  /**
   * @description: 获取授权
   */
  getSetting() {
    // 如果全局有经纬度则直接用全局的经纬度
    if (app.globalData.lat) {
      this.getAreaByName();
      this.getPrivincesAndCategory();
      return;
    }
    wx.getSetting()
      .then((res) => {
        console.log("res: getSetting", res);
        if (!res.authSetting["scope.userLocation"]) {
          this.authorize();
        } else {
          this.getLocation();
        }
      })
      .catch((err) => {
        console.log("err: getSetting", err);
      });
  },

  authorize() {
    wx.authorize({
      scope: "scope.userLocation",
    })
      .then((res) => {
        console.log("res: authorize", res);
        this.getLocation();
      })
      .catch((err) => {
        console.log("err: authorize", err);
        this.getLocation();
      });
  },

  // 获取定位信息
  getLocation() {
    wx.getLocation({ type: "wgs84" })
      .then((res) => {
        console.log("res: getLocation", res);
        // 将经纬度放入全局globalData
        app.globalData = {
          ...app.globalData,
          lat: res.latitude,
          lon: res.longitude,
        };
        this.getAreaByName();
        this.getPrivincesAndCategory();
      })
      .catch((err) => {
        console.log("err: getLocation", err);
        this.getPrivincesAndCategory();
      });
  },

  /**
   * @description:
   */
  getPrivincesAndCategory() {
    const p1 = this.areaProvinces();
    const p2 = this.vaccineCategoryList();
    const p3 = this.miniAppBanners();
    Promise.all([p1, p2, p3])
      .then((result) => {
        const [provincesList, typeList = []] = result || [];
        const { filterResult } = this.data;
        if (filterResult.vaccineCategoryId > 0) {
          this.choosetype(typeList, 1);
        }
        this.setData({
          typeList,
          provincesList,
        });
        this.getList();
      })
      .catch((err) => {
        console.log("err: getPrivincesAndCategory", err);
        this.handlePageError("error");
      });
  },

  /**
   * @description: 获取疫苗类型数据
   */
  vaccineCategoryList() {
    return new Promise((resolve, reject) => {
      return api.vaccineCategoryList({
        // 调用接口，传入参数
        data: {},
        success: (res) => {
          if (+res.code === 0) {
            const dataList = (res.data.dataList || []).filter(item => item.show);
            const newDataList = [
              { id: -100, name: "全部", sortIndex: 1000000 },
            ];
            dataList.forEach((item, index) => {
              if (item.show) {
                item.sortIndex =
                  this.data.catId === item.id
                    ? dataList.length + 10
                    : dataList.length - index;
                newDataList.push(item);
              }
            });
            newDataList.sort((a, b) => b.sortIndex - a.sortIndex);
            resolve(newDataList);
          } else {
            reject();
          }
        },
        fail: (err) => {
          reject();
        },
      });
    });
  },

  /**
   * @description: 获取省份数据
   */
  areaProvinces() {
    return new Promise(function (resolve, reject) {
      return api.areaProvinces({
        data: {},
        success: (res) => {
          if (res.code * 1 === 0) {
            resolve([{ id: -100, name: "全国" }, ...res.data]);
          } else {
            reject();
          }
        },
        fail: (err) => {
          reject();
        },
      });
    });
  },

  /**
   * @description: 获取地区名称
   * @param {*} areaId
   */
  areaInfo(areaId) {
    api.areaInfo({
      // 调用接口，传入参数
      data: { areaId },
      success: (res) => {
        this.setData({
          areaTxt: res.data.name,
        });
      },
    });
  },

  /**
   * @description: 获取定位名称
   */
  getAreaByName() {
    api.getAreaByNameV2({
      data: {
        lat: app.globalData.lat,
        lon: app.globalData.lon,
      },
      success: (res) => {
        this.setData({
          locationName: +res.code === 0 && res.data ? res.data.name : "全国",
        });
      },
      fail: () => {
        this.setData({
          locationName: "全国",
        });
      },
    });
  },

  miniAppBanners() {
    api.miniAppBanners({
      data: {
        platform: 2,
      },
      success: (res) => {
        if (+res.code === 0) {
          this.setData({
            banner: res.data,
          });
        }
      },
      fail: (err) => {
        console.log("err: ", err);
      },
    });
  },

  getMiniAppFullScreenAdvV2() {
    api.getMiniAppFullScreenAdvV2({
      data: {
        platform: 2,
      },
      success: (res) => {
        const { code, data } = res;
        if (code === 0 && data && data.productActivity) {
          this.setData({
            adInfo: data.productActivity,
          });
        }
      },
    });
  },

  getShowPrivacy () {
    api.showPrivacy({
      data: {
        source: 2, // 1、app    2、小程序
      },
      success: (res) => {
        if (+res.code === 0) {
          this.setData({
            privacyData: res.data
          })
        }
      }
    })
  },

  onClosePrivacy() {
    const { privacyData } = this.data || {};
    privacyData.show = false
    this.setData({
      privacyData
    })
  },

  getList() {
    const { pageNum, filterResult } = this.data;
    let data = {
      pageNum,
      pageSize: 10,
      lat: app.globalData.lat,
      lon: app.globalData.lon,
      ...filterResult,
    };
    api.productVaccineProductV2List({
      // 调用接口，传入参数
      data,
      success: (res) => {
        let pageFooterType = "";
        // 报错
        if (+res.code !== 0) {
          return this.handlePageError("error");
        }
        // 无数据
        if (res.data.total <= 0) {
          return this.handlePageError("nodata");
        }

        // 数据只够一页展示end
        if (pageNum === 1 && res.data.total <= 10) {
          pageFooterType = "end";
        }
        // 正常数据
        const dataList = this.dataAdatar(res.data.dataList || []);
        this.setData({
          dataList:
            pageNum > 1 ? [...this.data.dataList, ...dataList] : dataList,
          totalPage: +res.data.totalPage,
          recommend: res.data.recommend,
          loading: false,
          feedLoading: false,
          once: true,
          pageFooterType,
          pageErrorType: "",
        });
      },
      fail: (err) => {
        this.handlePageError("error");
      },
    });
  },
  /**
   * @description: 处理页面异常
   */
  handlePageError(type) {
    const { pageNum, once } = this.data;
    this.setData({
      pageErrorType: type,
      pageErrorFixed: pageNum === 1 ? !once : false,
      loading: false,
      feedLoading: false,
    });
  },

  dataAdatar(data) {
    return data.map((item, index) => {
      return {
        id: index,
        ...item,
      };
    });
  },

  authorChoose() {
    wx.openSetting({
      success: () => {
        this.getLocation();
      },
    });
  },

  onSearch(e) {
    this.setData(
      {
        filterResult: e.detail,
        pageNum: 1,
        pageFooterType: "",
      },
      () => {
        this.getList();
      }
    );
  },
  onSecondSearch(e) {
    const { typeList } = this.data;
    const { _filterResult, index, _currentSecondFilterSort } = e.detail;
    typeList[index]["sortIndex"] = _currentSecondFilterSort;
    this.setData(
      {
        filterResult: _filterResult,
        typeList: typeList.sort((a, b) => b.sortIndex - a.sortIndex),
        feedLoading: true,
        pageFooterType: "",
        pageNum: 1,
      },
      () => {
        this.choosetype(typeList, 1);
        this.getList();
      }
    );
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const { pageNum, totalPage } = this.data;
    if (pageNum >= totalPage) {
      this.setData({
        pageFooterType: "end",
      });
    } else {
      this.setData(
        {
          pageNum: pageNum + 1,
          pageFooterType: "ing",
        },
        () => {
          this.getList();
        }
      );
    }
  },

  onRetry() {
    const { once } = this.data;
    this.setData(
      {
        pageFooterType: "ing",
        loading: !once,
      },
      () => {
        if (once) {
          this.getList();
        } else {
          this.getPrivincesAndCategory();
        }
      }
    );
  },

  openMessage() {
    this.setData({
      showWaringMessage: true,
    });
  },

  closeMessage() {
    this.setData({
      showWaringMessage: false,
    });
  },

  jumpSearch() {
    withTokenFn(() => {
      throttle(() => {
        wx.navigateTo({
          url: "../search/index",
        });
      }, 2000);
    });
  },

  handleModel() {
    const that = this;
    const { adInfo = {} } = that.data;
    // 跳客服
    if (+adInfo.contentType === 6) {
      this.jumpConsultByThrottle2();
    } else if (+adInfo.contentType === 8) {
      withTokenFn(() => {
        throttle(() => {
          wx.navigateTo({
            url: `../detail/detail?productMirrorId=${adInfo.content}&type=1`,
          });
          that.setData({
            adInfo: null,
          });
        }, 2000);
      });
    } else {
      this.setData({
        adInfo: null,
      });
    }
  },

  closeModel() {
    this.setData({
      adInfo: null,
    });
  },

  jumpConsultByThrottle2: throttle2(function () {
    this.messageCompany();
  }, 2000),

  messageCompany() {
    withTokenFn(() => {
      customerApi.messageCompany({
        data: {},
        success: (res) => {
          if (res.code * 1 === 0) {
            app.globalData.customerChoose = res.data.conversation;
            wx.navigateTo({
              url: `../customerIntelligent/index`,
            });
            this.setData({
              adInfo: null,
            });
          }
        },
      });
    });
  },

  /**
   * @description: 点击banner
   */
  jumpBanner(e) {
    const { item = {} } = e.currentTarget.dataset;
    // 跳客服
    if (+item.contentType === 6) {
      this.jumpConsultByThrottle2();
    } else if (+item.contentType === 8) {
      withTokenFn(() => {
        throttle(() => {
          wx.navigateTo({
            url: `../detail/detail?productMirrorId=${item.content}&type=1`,
          });
        }, 2000);
      });
    }
  },

  switch1Change(e) {
    const { value } = e.detail;
    wx.clearStorageSync();
    wx.setStorageSync("devVersion", value);
    this.setData({
      devVersion: value,
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
